﻿using System;
using System.IO;
using System.Linq;

namespace CustomerContactSystem.WebForms.Enquiries.Documents {
    public partial class Edit : BasePage {
        protected void Page_Load(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, true, "id,documentid")) {
                return;
            }

            EnquiryIdCaption.Text = Request.QueryString["id"];
            EnquiryIdCaption.NavigateUrl = "~/Enquiries/View.aspx?id=" + Request.QueryString["id"];

            GetDocument();
        }

        private void GetDocument() {
            var enquiryId = int.Parse(Request.QueryString["id"]);
            var documentId = int.Parse(Request.QueryString["documentid"]);
            var enquiry = EnquiryRepository.GetById(enquiryId);
            var document = enquiry.Documents.SingleOrDefault(d => d.Id == documentId);

            if (document == null) {
                return;
            }

            DocumentName.Text = document.DocumentName;
            DocumentDescription.Text = document.DocumentDescription;
        }

        protected void SubmitDocumentClick(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, false, "id,documentid")) {
                return;
            }

            var enquiryId = int.Parse(Request.QueryString["id"]);
            var documentId = int.Parse(Request.QueryString["documentid"]);
            var enquiry = EnquiryRepository.GetById(enquiryId);
            var document = enquiry.UpdateDocument(LoggedUser.DisplayName, documentId, DocumentName.Text,
                                                  DocumentDescription.Text); 
            
            if (document == null) {
                return;
            }

            if (!IsValidObject(document, SubmitDocumentResultMessage) || !IsValidUpload()) {
                return;
            }

            if (DocumentFile.PostedFile != null && DocumentFile.PostedFile.ContentLength > 0) {
                var fileName = GetUploadedFileName();
                var fileExtension = fileName.Substring(fileName.LastIndexOf(".", StringComparison.Ordinal) + 1).ToLower();

                DocumentFile.PostedFile.SaveAs(Server.MapPath("~/Docs/" + document.SavePath() + document.FileName));

                if (fileExtension != document.DocumentType) {
                    File.Move(Server.MapPath("~/Docs/" + document.SavePath() + document.FileName),
                              Server.MapPath("~/Docs/" + document.SavePath() +
                                             document.FileName.Replace(document.DocumentType, fileExtension)));
                    document.FileName = document.FileName.Replace(document.DocumentType, fileExtension);
                    document.DocumentType = fileExtension;
                }
            }

            EnquiryRepository.Update(enquiry);

            Response.Redirect("~/Enquiries/View.aspx?id=" + document.Enquiry.Id);
        }

        private bool IsValidUpload() {
            if (DocumentFile.PostedFile != null && DocumentFile.PostedFile.ContentLength > 0) {
                var fileName = GetUploadedFileName();
                var fileExtension = fileName.Substring(fileName.LastIndexOf(".", StringComparison.Ordinal) + 1).ToLower();
                var allowedExtensions = ConfigSettings.AllowedFileExtensions.Split(',');

                return allowedExtensions.Any(allowedExtension => allowedExtension == fileExtension);
            }

            return true;
        }

        private string GetUploadedFileName() {
            var fileName = DocumentFile.PostedFile.FileName;
            return fileName.Substring(fileName.LastIndexOf("\\", StringComparison.Ordinal) + 1);
        }
    }
}